package com.minyifang.wcspf.work.ui.widgets;

import android.content.Context;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.LinearLayout;

public class ShadowLinearLayout extends LinearLayout {

    private Paint mPaint;
    private RectF mRectF;
    private float mSideOffset;
    private float mRadius;
    private float mShadowRadius;
    private float mShadowVerticalOffset;

    public ShadowLinearLayout(Context context) {
        this(context, null);
    }

    public ShadowLinearLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ShadowLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        float density = context.getResources().getDisplayMetrics().density;
        mSideOffset = density * 6;
        mRadius = density * 6;
        mShadowRadius = 2 * density;
        mShadowVerticalOffset = 1 * density / 2;
        setLayerType(LAYER_TYPE_SOFTWARE, null);
        initPaint();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mRectF = new RectF(mSideOffset, mSideOffset, w - mSideOffset, h - mSideOffset);
    }

    private void initPaint() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        mPaint.setColor(Color.BLACK);
        mPaint.setMaskFilter(new BlurMaskFilter(mShadowRadius, BlurMaskFilter.Blur.NORMAL));
        mPaint.setAlpha(15);
        canvas.save();
        canvas.translate(0, mShadowVerticalOffset);
        canvas.drawRoundRect(mRectF, mRadius, mRadius, mPaint);
        canvas.restore();
        mPaint.setAlpha(255);
        mPaint.setColor(Color.WHITE);
        mPaint.setMaskFilter(null);
        canvas.drawRoundRect(mRectF, mRadius, mRadius, mPaint);
        super.dispatchDraw(canvas);
    }
}
